<template>
  <div class="history-trends">
    <!-- 时间范围选择 -->
    <div class="time-filter">
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="YYYY-MM-DD"
      />
      <el-select v-model="selectedMetric" placeholder="请选择指标">
        <el-option
          v-for="option in metricOptions"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
      <el-button type="primary" @click="filterData">确认</el-button>
    </div>

    <!-- ECharts 图表 -->
    <div class="chart-container" ref="chartContainer"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { ref, onMounted } from "vue";

export default {
  name: "HistoryTrends",
  components: {},

  data() {
    return {
      dateRange: [], // 时间范围
      selectedMetric: "flow_rate", // 默认指标
      metricOptions: [
        { label: "单位时间内通过水量 (立方米/秒)", value: "flow_rate" },
        { label: "水面高度 (米)", value: "water_level" },
        { label: "湖库水量 (立方米)", value: "storage_volume" },
        { label: "流入水流总量 (立方米/秒)", value: "inflow_runoff" },
        { label: "流出湖泊水量 (立方米/秒)", value: "outflow_runoff" },
        { label: "湖面蒸发水量 (立方米/天)", value: "evaporation" },
        { label: "湖泊及其集水区内降雨量 (毫米)", value: "precipitation" },
        { label: "生态系统健康最小流量 (立方米/秒)", value: "min_ecological_flow" },
        { label: "最大允许取水量 (立方米/秒)", value: "max_permissible_withdrawal" },
        { label: "防洪限值 (米或立方米)", value: "flood_control_limit" },
      ],
      data: [], // 存储解析后的数据
      alpha: 0.3, // 单指数平滑系数
    };
  },

  methods: {
    // 加载并解析数据
    async loadData() {
      try {
        const response = await fetch(
          "/csv/hma_quantity_output.json"
        );
        const rawData = await response.json();

        // 处理数据
        this.data = rawData.map((item) => {
          const createTime = item.create_time.split(" ")[0];
          return {
            date: createTime,
            flow_rate: parseFloat(item.flow_rate),
            water_level: parseFloat(item.water_level),
            storage_volume: parseFloat(item.storage_volume),
            inflow_runoff: parseFloat(item.inflow_runoff),
            outflow_runoff: parseFloat(item.outflow_runoff),
            evaporation: parseFloat(item.evaporation),
            precipitation: parseFloat(item.precipitation),
            min_ecological_flow: parseFloat(item.min_ecological_flow),
            max_permissible_withdrawal: parseFloat(item.max_permissible_withdrawal),
            flood_control_limit: parseFloat(item.flood_control_limit),
          };
        });
      } catch (error) {
        console.error("加载数据失败:", error);
      }
    },

    // 筛选数据
    filterData() {
      const [startDate, endDate] = this.dateRange;
      const selectedMetric = this.selectedMetric;

      // 过滤数据
      const filteredData = this.data.filter((item) => {
        const date = new Date(item.date);
        return date >= new Date(startDate) && date <= new Date(endDate);
      });

      // 提取日期和指标值
      const dates = filteredData.map((item) => item.date);
      const metricValues = filteredData.map((item) => item[selectedMetric]);

      // 渲染图表
      this.renderChart(dates, metricValues, selectedMetric);
    },

    // 渲染 ECharts 图表
    renderChart(dates, metricValues, metric) {
      const chartContainer = this.$refs.chartContainer;
      if (!chartContainer) return;


      // 初始化 ECharts 实例
      const chart = echarts.init(chartContainer);

      // 计算单指数平滑数据
      const singleIndexData = this.calculateSingleExponentialSmoothing(
        metricValues,
        this.alpha
      );

      // 配置 ECharts 图表
      const option = {
        // title: {
        //   text: metric,
        //   left: "center",
        // },
        tooltip: {
          trigger: "axis",
        },
        xAxis: {
          type: "category",
          data: dates,
          position: "bottom",
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            name: metric,
            type: "line",
            data: metricValues,
            smooth: true,
          },
          {
            name: "单指数平滑预测",
            type: "line",
            data: singleIndexData,
            smooth: true,
            lineStyle: {
              color: "red",
              width: 2,
            },
          },
        ],
      };

      // 渲染图表
      chart.setOption(option);
    },
    // 单指数平滑法计算
    calculateSingleExponentialSmoothing(data, alpha) {
      const result = [];
      let prevSmoothed = data[0]; // 初始值为第一个数据点
      result.push(prevSmoothed);

      for (let i = 1; i < data.length; i++) {
        const smoothed = alpha * data[i] + (1 - alpha) * prevSmoothed;
        result.push(smoothed);
        prevSmoothed = smoothed;
      }

      return result;
    },
  },

  mounted() {
    this.loadData();
  },
};
</script>

<style scoped>
.history-trends {
  padding: 20px;
}

.time-filter {
  margin-bottom: 20px;
  /* display: flex; */
  gap: 10px;
  width: 2000px;
}

.chart-container {
  margin-top: 200px;
  width: 100%;
  height: 500px;
}
.el-select{
  margin-left: 20px;
  margin-right: 20px;
  width: 400px;
}
</style>